<?php

namespace App\Http\Controllers\Api;

use App\Events\AllotCustomerEvent;
use App\Http\Requests\CoustomerRequest;
use App\Http\Requests\UpdateStatusRequest;
use App\Http\Resources\CoustomerAreaCollection;
use App\Http\Resources\CoustomerCollection;
use App\Http\Resources\CoustomerMianjiCollection;
use App\Http\Resources\CustomerResource;
use App\Http\Resources\FollowCollection;
use App\Http\Resources\SeaCollection;
use App\model\Area;
use App\model\baiduForm;
use App\model\Coustomer;
use App\model\CustomerFollow;
use App\model\Industry;
use App\model\Project;
use App\model\SendNoticeUser;
use App\model\Source;
use App\model\tengxunForm;
use App\Repository\CustomerRepository;
use App\Repository\WechatRepository;
use App\SeaCustomer;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use function PhpParser\filesInDir;

class CoustomerController extends Controller
{
    protected $customerRepository;

    public function __construct(CustomerRepository $customerRepository)
    {
        $this->customerRepository = $customerRepository;
    }

    public function create(CoustomerRequest $request)
    {
        \DB::transaction(function () use ($request) {
            //查看用户是否是推广员
            $user = User::find(\Auth::guard('api')->id());
            $coustmoer = new Coustomer();
            $coustmoer->mobile = $request->get('mobile');
            $coustmoer->company_name = $request->get('company_name');
            $coustmoer->name = $request->get('name');
            $coustmoer->industry_id = $request->get('industry_id');
            $coustmoer->source_id = $request->get('source_id');
            $coustmoer->project_id = $request->get('project_id');
            $coustmoer->user_id = \Auth::guard('api')->id();
            if ($user->hasPermissionTo('saleman')) {
                $coustmoer->writer_id = \Auth::guard('api')->id();
                $coustmoer->status = Coustomer::No_Follow_Up;
            } else {
                $coustmoer->status = Coustomer::Follow_up;
            }
            $coustmoer->demand_id = $request->get('demand_id');
            $coustmoer->area_id = $request->get('area_id');
            $coustmoer->city1 = $request->get('city1');
            $coustmoer->city2 = $request->get('city2');
            $coustmoer->save();
            $coustmoerFollow = new CustomerFollow();
            $coustmoerFollow->image = $request->get('image');
            $coustmoerFollow->customer_id = $coustmoer->customer_id;
            $coustmoerFollow->desc = $request->get('desc');
            $coustmoerFollow->user_id = \Auth::guard('api')->id();
            $coustmoerFollow->save();
            $customer = new CustomerRepository();
            $customer->sendXiaoshou($coustmoer);
        });
        return response()->json(
            [
                'status' => 1,
                'message' => '新增成功',
            ]
        );
    }

    public function update(Request $request)
    {

        $coustmoer = Coustomer::find($request->get('customer_id'));
        // $coustmoer->mobile=$request->get('mobile');
        $coustmoer->company_name = $request->get('company_name');
        $coustmoer->name = $request->get('name');
        $coustmoer->industry_id = $request->get('industry_id');
        // $coustmoer->source_id=$request->get('source_id');
        // $coustmoer->project_id=$request->get('project_id');
        $coustmoer->demand_id = $request->get('demand_id');
        $coustmoer->area_id = $request->get('area_id');
        $coustmoer->city1 = $request->get('city1');
        $coustmoer->city2 = $request->get('city2');
        $coustmoer->save();
        $coustmoerFollow = CustomerFollow::where('customer_id', $coustmoer->customer_id)->orderBy('created_at', 'asc')->first();
        if (!$coustmoerFollow) {
            $coustmoerFollow = new CustomerFollow();
            $coustmoerFollow->customer_id = $coustmoer->customer_id;
        }
        $coustmoerFollow->image = $request->get('image');
        $coustmoerFollow->customer_id = $coustmoer->customer_id;
        $coustmoerFollow->desc = $request->get('desc');
        $coustmoerFollow->user_id = \Auth::guard('api')->id();
        $coustmoerFollow->save();
        return response()->json(
            [
                'status' => 1,
                'message' => '修改成功',
            ]);
    }

    /**
     * 客户列表
     * @authenticated
     * @bodyParam industry_id int required  客户id. Example:null
     * @bodyParam project_id int 项目id Example:null
     * @bodyParam source_id int 来源id Example:null
     * @bodyParam search_key string 搜索key名字手机号 Example:
     * @bodyParam time   string yesterday week mouth
     *
     */
    public function index(Request $request)
    {//客户列表
        $user = $request->user();
        $Coustomer = Coustomer::with(['area', 'demand', 'source', 'sign', 'industry']);
        if (!$user->checkPermissionTo('all') && !$request->get('project_id')) {
            $Coustomer = $Coustomer->whereIn('project_id', $user->project_id)->where('project_id', '!=', 0);
        }
        if (!$user->checkPermissionTo('saleman')) {
            $Coustomer = $Coustomer->where('user_id', $user->id);
        }
        $Coustomer = $Coustomer->when($request->get('industry_id'), function ($query) use ($request) {
            $query->where('industry_id', $request->get('industry_id'));
        })
            ->when($request->get('source_id'), function ($query) use ($request) {
                $query->where('source_id', $request->get('source_id'));
            })
            ->when($request->get('project_id'), function ($query) use ($request) {
                $query->where('project_id', $request->get('project_id'));
            })
            ->when($request->get('time'), function ($query) use ($request) {
                $time = $request->get('time');
                if ($time == 'yesterday') {
                    $start_time = Carbon::yesterday();
                    $end_time = Carbon::today();
                } elseif ($time == 'week') {
                    $start_time = Carbon::today()->addDays(-(Carbon::getWeekendDays())['0'] + 1);
                    $end_time = Carbon::today()->addDays((Carbon::getWeekendDays())['1'] + 2);

                } elseif ($time == 'month') {
                    $start_time = Carbon::now()->firstOfMonth();
                    $end_time = Carbon::now()->lastOfMonth();
                }
                $query->whereBetween('created_at', [$start_time, $end_time]);
            })->when($request->get('search_key'), function ($query) use ($request) {

                $query->where(function ($query) use ($request) {
                    $query->where('name', 'like', '%' . $request->get('search_key') . '%')
                        ->orWhere('mobile', 'like', '%' . $request->get('search_key') . '%');
                });
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        return new CoustomerCollection($Coustomer);
    }

    /**
     * 管理客户列表
     * @authenticated
     * @bodyParam industry_id int  行业id. Example:null
     * @bodyParam project_id int 项目id Example:null
     * @bodyParam source_id int 来源id Example:null
     * @bodyParam search_key string 搜索key名字手机号 Example:
     */
    public function list(Request $request)
    {
        //判断
        $user = \Auth::guard('api')->user();
        $user_id = $request->user_id;

        $Coustomer = Coustomer::with(['area', 'demand', 'source', 'sign', 'industry']);
        if (!$user->checkPermissionTo('all') && !$request->get('project_id')) {
            $Coustomer = $Coustomer->whereIn('project_id', $user->project_id)->where('project_id', '!=', 0);
        }

        if ($user_id) {
            $Coustomer = $Coustomer->where('user_id', $user_id);
        }

        $Coustomer = $Coustomer->when($request->get('project_id'), function ($query) use ($request) {
            $query->where('project_id', $request->get('project_id'));
        });
        $Coustomer = $Coustomer->when($request->get('source_id'), function ($query) use ($request) {
            $query->where('source_id', $request->get('source_id'));
        })->when($request->get('industry_id'), function ($query) use ($request) {
            $query->where('industry_id', $request->get('industry_id'));
        })
            ->when($request->get('time'), function ($query) use ($request) {
                $time = $request->get('time');
                if ($time == 'yesterday') {
                    $start_time = Carbon::yesterday();
                    $end_time = Carbon::today();
                } elseif ($time == 'week') {
                    $start_time = Carbon::today()->addDays(-(Carbon::getWeekendDays())['0'] + 1);
                    $end_time = Carbon::today()->addDays((Carbon::getWeekendDays())['1'] + 2);

                } elseif ($time == 'month') {
                    $start_time = Carbon::now()->firstOfMonth();
                    $end_time = Carbon::now()->lastOfMonth();
                }
                $query->whereBetween('created_at', [$start_time, $end_time]);
            })
            ->when($request->get('search_key'), function ($query) use ($request) {
                $query->where(function ($query) use ($request) {
                    $query->where('name', 'like', '%' . $request->get('search_key') . '%')
                        ->orWhere('mobile', 'like', '%' . $request->get('search_key') . '%');
                });
            })
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        return new CoustomerCollection($Coustomer);
    }

    /**
     * 客户详情
     * @authenticated
     * @bodyParam customer_id int required 客户id. Example:4
     */
    public function detail(Request $request)
    {
        $coustomer = Coustomer::with(['industry', 'sign', 'project', 'demand', 'area', 'source', 'beizhu', 'zhaoshangDemand', 'follow' => function ($query) {
            $query->with('user')->orderBy('follow_id', 'desc');
        }])
            ->where('customer_id', $request->get('customer_id'))->first();
        //  $this->authorize('view',$coustomer);
        $user = \Auth::guard('api')->user();
        if ($coustomer->user_id == 0) {
            if ($user->hasPermissionTo('hide') && !$user->hasPermissionTo('all')) {
                $coustomer->mobile = substr_replace($coustomer->mobile, '****', 3, 4);
            }
        }
        if ($request->sea == 1) {
            $coustomer->mobile = substr_replace($coustomer->mobile, '****', 3, 4);
        }
        return new CustomerResource($coustomer);
    }

    public function allot(Request $request)
    {
        $validator = Validator::make($request->all(), ['user_id' => 'required', 'customer_id' => 'required']);
        \Log::info($request->get('user_id'));
        if ($validator->fails()) {
            return response()->json(
                [
                    'status' => 0,
                    'message' => '参数缺失',
                ]
            );
        }
        $coustomer = Coustomer::findOrFail($request->get('customer_id'));

        $coustomer->user_id = $request->get('user_id');
        $coustomer->status = Coustomer::Follow_up;

        $coustomer->save();
        if (config('app.env') == 'production') {
            event(new AllotCustomerEvent(User::find($request->get('user_id')), $coustomer));
            $wechat = new WechatRepository();
            $wechat->sendXiaoshouMessage(User::find($request->get('user_id')), $coustomer, false);
        }
        return response()->json(
            [
                'status' => 1,
                'message' => '分配成功',
            ]
        );
    }

    //更改状态
    public function updateStatus(UpdateStatusRequest $request)
    {
        $coustomer = Coustomer::find($request->get('customer_id'));
        $coustomer->status = $request->get('status');
        $coustomer->save();
        return response()->json(
            [
                'status' => 1,
                'message' => '保存成功',
            ]
        );
    }

    //头条表单提交
    public function toutiaoForm(Request $request)
    {
        Log::info('头条信息', $request->all());
        $v = $request->all();
        if (isset($v['id'])) {
            $v['clue_id'] = $v['id'];
        }
        if (isset($v['app_name'])) {
            $v['appname'] = $v['app_name'];
        }
        $v['gender'] = 0;
        $project_id = $request->input('project_id', '');
        $project = Project::find($project_id);
        $create_user_id = $request->input('create_user_id', 1);
        $coustomer = Coustomer::where('clue_id', '=', $v['clue_id'])
            ->first();

        if (!$coustomer) {
            $coustomer = new Coustomer();
            $coustomer->name = $v['name'];
            $coustomer->mobile = $v['telphone'];
            if (isset($v['location'])) {
                $city = explode('+', $v['location']);
                $coustomer->city1 = $city[0];
                $coustomer->city2 = $city[1];
            }
            $coustomer->source_id = 9;
            $coustomer->project_id = $project_id;
            if (isset($v['remark_dict']['所在行业'])) {
                $industry = Industry::firstOrCreate(['name' => $v['remark_dict']['所在行业'], 'project_id' => $project_id]);
                $coustomer->industry_id = $industry->industry_id;
            }
            $coustomer->clue_id = $v['clue_id'];
            if (isset($v['remark_dict']['需求面积'])) {
                $area = Area::firstOrCreate(['name' => $v['remark_dict']['需求面积']]);
                $coustomer->area_id = $area->id;
            }
            if (isset($v['remark_dict']['需求的面积'])) {
                $area = Area::firstOrCreate(['name' => $v['remark_dict']['需求的面积']]);
                $coustomer->area_id = $area->id;
            }
            if (isset($v['remark_dict']['所需面积'])) {
                $area = Area::firstOrCreate(['name' => $v['remark_dict']['所需面积']]);
                $coustomer->area_id = $area->id;
            }
            if (isset($v['remark_dict']['所需求的面积'])) {
                $area = Area::firstOrCreate(['name' => $v['remark_dict']['所需求的面积']]);
                $coustomer->area_id = $area->id;
            }
            if (isset($v['remark_dict']['所需厂房面积'])) {
                $area = Area::firstOrCreate(['name' => $v['remark_dict']['所需厂房面积']]);
                $coustomer->area_id = $area->id;
            }
            $coustomer->adv_name = $v['ad_name'] ?? '';
            $coustomer->external_url = $v['external_url'];
            $coustomer->sex = $v['gender'];
            $coustomer->save();
            //销售数据
            $this->customerRepository->sendXiaoshou($coustomer);
            return [
                'code' => '0',
                'message' => 'success1重复'
            ];
        } else {
            return [
                'code' => '0',
                'message' => 'success1重复'
            ];
        }

    }

    //百度表单提交
    public function baiduForm(Request $request)
    {
        $data = $request->getContent();
        $form = new baiduForm();
        $form->data = $data;
        $form->save();
        $customerRes = new CustomerRepository();
        $customerRes->newcustomerBaidu($form, $request->get('project_id'));
        \Log::error('success');
        return "success";
    }

    //腾讯表单提交
    public function tengxunForm(Request $request)
    {
        $data = $request->getContent();
        $form = new tengxunForm();
        $form->data = $data;
        $form->save();
        $customerRes = new CustomerRepository();
        $customerRes->newcustomer($form, $request->get('project_id'));
        return response()->json(
            [
                'code' => 0,
                'msg' => 'success'
            ]
        );
    }

    //公海客户
    public function seaCoustomer(Request $request)
    {
        //判断
        $user = \Auth::guard('api')->user();
        $coustomer = Coustomer::with(['industry', 'area'])->when($request->industry_id, function ($query) use ($request) {
            $query->where('industry_id', '=', $request->industry_id);
        })->when($request->search_key, function ($query) use ($request) {
            $query->where(function ($query) use ($request) {
                $query->orWhere('name', 'like', '%' . $request->search_key . '%');
            });
        })->when($request->city2, function ($query) use ($request) {
            $query->where('city2', $request->city2);

        })
            ->when($request->mianji_id, function ($query) use ($request) {
                $query->where('area_id', $request->mianji_id);
            })
            ->where('is_sea', '=', 1)
            ->whereDoesntHave('sea')
            ->whereDoesntHave('project', function ($q) {
                $q->where('project.is_sea', '=', 0);
            })
            ->paginate(10);
        return new SeaCollection($coustomer);
    }

    //领取客户
    public function receive(Request $request)
    {
        $user = \Auth::guard('api')->user();
        $customer_id = $request->customer_id;
        $project_id = $request->project_id;
        //判断是否领取过
        $seaCustomer = SeaCustomer::where('customer_id', '=', $customer_id)->first();
        if ($seaCustomer) {
            return response()->json([
                'code' => 1,
                'msg' => '已经领取过'
            ]);
        }
        //判断别人在三天内是否领取过

        $customerOld = Coustomer::find($customer_id);
        //判断是否是同一个项目
        if (in_array($customerOld->project_id, $user->project_id)) {
            return response()->json([
                'code' => 1,
                'msg' => '同一个项目的不能领取'
            ]);
        }
        //判断领取了几个
        $seaCount = SeaCustomer::where('created_at', '>', Carbon::today())->whereUserId($user->id)->count();
        if ($seaCount > 30) {
            return response()->json([
                'code' => 1,
                'msg' => '今日领取超过30个'
            ]);
        }

        $customer = new Coustomer();
        $customer->mobile = $customerOld->mobile;
        $customer->company_name = $customerOld->company_name;
        $customer->industry_id = $customerOld->industry_id;
        $customer->project_id = $project_id;
        $source = Source::where('name', '公海')->first();
        if (!$source) {
            $source = new Source();
            $source->name = '公海';
            $source->save();
        }
        $customer->source_id = $source->source_id;
        $customer->name = $customerOld->name;
        $customer->area_id = $customerOld->area_id;
        $customer->demand_id = $customerOld->demand_id;
        $customer->city1 = $customerOld->city1;
        $customer->city2 = $customerOld->city2;
        $customer->status = Coustomer::No_Follow_Up;
        $customer->writer_id = $user->id;
        $customer->customer_level_id = $customerOld->customer_level_id;
        $customer->wechat = $customerOld->wechat;
        $customer->tel = $customerOld->tel;
        $customer->company_address = $customerOld->company_address;
        $customer->sex = $customerOld->sex;
        $customer->adv_name = $customerOld->adv_name;
        $customer->external_url = $customerOld->external_url;
        $customer->clue_id = $customerOld->clue_id;
        $customer->is_sea = 0;
        $customer->receive_id = $customer_id;
        $customer->next_time = Carbon::now();
        $customerOld->next_time = Carbon::now();
        $customerOld->save();

        $customer->save();
        $seaCustomer = new SeaCustomer();
        $seaCustomer->user_id = $user->id;
        $seaCustomer->customer_id = $customer_id;
        $seaCustomer->save();
        return response()->json(
            [
                'code' => 0,
                'msg' => '领取成功'
            ]
        );

    }

    /**
     * 获取区域列表
     */
    public function area(Request $request)
    {
        $customer = Coustomer::where('is_sea', 1)->where('city2', '!=', '')->select('city2')->groupBy('city2')->get();
        return new CoustomerAreaCollection($customer);
    }

    /**
     * 获取面积
     */
    public function mianji(Request $request)
    {
        $customer = Coustomer::with('area')->where('is_sea', 1)->where('area_id', '!=', '')->select('area_id')->groupBy('area_id')->get();
        return new CoustomerMianjiCollection($customer);
    }
}
